
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Image,
  Dimensions,TouchableOpacity,FlatList
} from 'react-native';
import TopBar from '../../bar/TopBar'
import BASEURL from '../../api/api'
import Loading from '../../common/Loading'
import Toast, {DURATION} from 'react-native-easy-toast'
import Picker from 'react-native-picker';
import NoData from '../../common/NoData'
import {createDateData,getCurrentDate} from '../../common/common'
var {height, width} = Dimensions.get('window');
const dismissKeyboard = require('dismissKeyboard');
export default class MonitorDetail extends Component {
  static navigationOptions = ({ navigation }) =>{
    return{
      headerTitle:<TopBar title='监测详情' navigation = {navigation}/>,
      headerLeft:null,
    }
  };
  constructor(props){
    super(props)
    
    let time = getCurrentDate()
    this.state = ({
      emp:{},
      isHour:true,
      hyCode:this.props.navigation.getParam('hyCode'),
      dayFlowList:[],
      hourFlowList:[],
      data:[],
      dateData:[],
      currTime:time,
      startTime:time,
      endTime:time,
      timeType:0,//0-小时   1-开始时间  2-结束时间
      msg:'',
    })
  }
  componentWillMount(){
    this.fetchData()
  }
  componentDidMount(){
    this.getFlowListTime()
    this.setState({
      dateData:createDateData(),
    })
  }
  //打开日期选择
  _showDatePicker() {
    var currDate = new Date()
    var year = ''
    var month = ''
    var day = ''
    var currStr 
    var dateStr = ''
    if(this.state.timeType==0){
      dateStr = this.state.currTime
    } else if(this.state.timeType==1){
      dateStr = this.state.startTime
    } else if(this.state.timeType==2){
      dateStr = this.state.endTime
    }
    //console.log('dateStr',dateStr)
    year = dateStr.substring(0,4)
    month = parseInt(dateStr.substring(5,7))
    day = parseInt(dateStr.substring(8,10))
    //console.log('year',year)
    //console.log('month',month)
    //console.log('day',day)
    Picker.init({
      pickerTitleText:'时间选择',
      pickerCancelBtnText:'取消',
      pickerConfirmBtnText:'确定',
      selectedValue:[year+'年',month+'月',day+'日'],
      pickerBg:[255,255,255,1],
      pickerData: this.state.dateData,
      pickerFontColor: [33, 33 ,33, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
          var year = pickedValue[0].substring(0,pickedValue[0].length-1)
          var month = pickedValue[1].substring(0,pickedValue[1].length-1)
          month = month.padStart(2,'0')
          var day = pickedValue[2].substring(0,pickedValue[2].length-1)
          day = day.padStart(2,'0')
          let str = year+'-'+month+'-'+day
          if(this.state.timeType==0){
            this.setState({
              currTime:str,
            })
            setTimeout(()=>{
              this.getFlowListTime()
            },50)
          } else if(this.state.timeType==1){
            this.setState({
              startTime:str,
            })
            setTimeout(()=>{
              this.getFlowListDay()
            },50)
          } else if(this.state.timeType==2){
            this.setState({
              endTime:str,
            })
            setTimeout(()=>{
              this.getFlowListDay()
            },50)
          }
          
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }
  _selectDate(type){
    this.setState({
      timeType:type
    })
    setTimeout(()=>{
      this._showDatePicker()
    },50)
    
  }
  //按小时获取，取当天的
  getFlowListTime(){
    fetch(BASEURL+'getFlowListTime?hyCode='+this.state.hyCode+'&time='+this.state.currTime)
    .then(res=>res.json())
    .then(response=>{
      //console.log('res',response)
      if(response.falg){
        this.setState({
          data:response.flowList,
          hourFlowList:response.flowList,
          loading:false,
        })
      } else {
        this.setState({
          data:[],
          hourFlowList:[],
          loading:false,
          msg:response.message
        })
        //this.refs.toast.show('获取失败');
      }
    })
  }
  //按天获取
  getFlowListDay(){
    //console.log('start',this.state.startTime)
    //console.log('end',this.state.endTime)
    fetch(BASEURL+'getFlowListDay?hyCode='+this.state.hyCode
    +'&startTime='+this.state.startTime+'&endTime='+this.state.endTime)
    .then(res=>res.json())
    .then(response=>{
      //console.log('getFlowListDay=>res',response)
      if(response.falg){
        this.setState({
          dayFlowList:response.flowList,
          data:response.flowList,
          loading:false,
        })
      } else {
        this.setState({
          dayFlowList:[],
          data:[],
          loading:false,
          msg:response.message
        })
        //this.refs.toast.show('获取失败');
      }
    })
  }
  fetchData(){
    fetch(BASEURL+'getEmp?hyCode='+this.state.hyCode)
    .then(res=>res.json())
    .then(response=>{
      //console.log('res',response)
      if(response.falg){
        this.setState({
          emp:response.emp,
          loading:false,
        })
      } else {
        this.setState({
          loading:false,
        })
        this.refs.toast.show('获取失败');
      }
    })
  }
  _hour(){
    this.setState({
      isHour:!this.state.isHour
    })
    setTimeout(()=>{
      if(!this.state.isHour){ //天
        if(this.state.dayFlowList.length == 0){
          //console.log('获取天的数据')
          this.getFlowListDay()
        } else {
          //console.log('不用获取天的数据')
          this.setState({
            data:this.state.dayFlowList
          })
        }
        
      } else { //小时
        //console.log('点击的小时')
        this.setState({
          data:this.state.hourFlowList
        })
      }
    },50)
  }
  _separator = () => {
    return <View style={{height:1,backgroundColor:'#f0f0f0',
    marginLeft:20,marginRight:20,}}/>;
  }
  _keyExtractor = (item, index) => index.toString();
  _renderItem=({item})=>{
    return(
      <View style={styles.row}>
        <Text style={styles.column2}>{item.seq}</Text>
        <Text style={styles.column3}>{item.COLLECTION_TIME}</Text>
        <Text style={styles.column2}>{item.REPLAY_BASE_FLOW}m³/s</Text>
      </View>
    )
  }
  render(){
    let item = this.state.emp
    let isHour = this.state.isHour
    return(
      <View style={styles.container}>
        <View style={styles.headerStyle}>
          <View style={{padding:10}}>
            <Image style={styles.lefgImg} source={require('../../images/no-img.png')}/>
          </View>
          <View>
            <Text style={{fontSize:17,padding:5}}>{item.hy_name}</Text>
            <Text style={styles.subTitle}>所属河流：{item.river_name}</Text>
            <Text style={styles.subTitle}>地理位置：{item.com_locations}</Text>
          </View>
        </View>
        <View style={styles.itemBox}>
          <Item title='生态基流' num={item.environmental} unit='m³/s' color='#ff7843'/>
          <Line />
          <Item title='最小下泄量' num={item.min_flow} unit='m³/s' color='#ff7843'/>
          <Line />
          <Item title='实时监测流量' num={item.ecology_out_flow} unit='m³/s' color='#2cbf67'/>
        </View>
        <View style={{height:10,backgroundColor:'#f0f0f0'}}/>
        <View style={styles.titleStyle}>
          <View style={styles.header}>
            <Image source={require('../../images/monitor-data.png')}/>
            <Text style={styles.headerText}>监测数据</Text>
          </View>
          <View style={styles.rightBtn}>
            <TouchableOpacity  onPress={()=>{this._hour(true)}}
              //hitSlop={{left: 15}}
              style={[styles.switchView,styles.hour,isHour?styles.active:styles.noActive]}>
              <Text style={[styles.switchText,isHour?styles.activeT:styles.noActiveT]}>小时</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={()=>{this._hour(true)}}
              //hitSlop={{right: 15}}
              style={[styles.switchView,styles.day,!isHour?styles.active:styles.noActive]}>
              <Text style={[styles.switchText,!isHour?styles.activeT:styles.noActiveT]}>天</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={[styles.titleStyle,{borderBottomWidth:0}]}>
          <View style={styles.header}>
            <Image source={require('../../images/select-time.png')}/>
            <Text style={[styles.headerText,{marginLeft:8,color:'#777'}]}>时间选择</Text>
          </View>
          <View style={styles.rightBtn}>
            {!isHour?
            <View style={{flexDirection:'row',alignItems:'center'}}>
              <TouchableOpacity  onPress={()=>{this._selectDate(1)}} style={{marginRight:10}}>
                <Text >{this.state.startTime}</Text>
              </TouchableOpacity>
              <TouchableOpacity  onPress={()=>{this._selectDate(2)}}>
                <Text >{this.state.endTime}</Text>
              </TouchableOpacity>
            </View>:
            <TouchableOpacity  onPress={()=>{this._selectDate(0)}} style={{marginRight:10}}>
              <Text >{this.state.currTime}</Text>
            </TouchableOpacity>
            }
          </View>
        </View>
        <View style={{height:6,backgroundColor:'#f0f0f0'}}/>
        <HeaderComponent />
        {this.state.data.length==0?
        <NoData  msg={this.state.msg}/>
        :
        <FlatList
          style={{flex:1}}
          data={this.state.data}
          keyExtractor={this._keyExtractor}
          ItemSeparatorComponent={this._separator}
          renderItem={this._renderItem}
        />
      }
        
        <Toast ref="toast" position='bottom' positionValue={200}/>
      </View>
    )
  }
}
class HeaderComponent extends Component{
  render(){
    return(
      <View style={[styles.row,styles.rowHeader]}>
        <Text style={styles.column2}>序号</Text>
        <Text style={styles.column3}>时间</Text>
        <Text style={styles.column2}>监测流量</Text>
      </View>
    )
  }
}
class Line extends Component{
  render(){
    return(
      <View style={{width:1,height:20,backgroundColor:'#ccc'}}></View>
    )
  }
}
class Item extends Component{
  render(){
    return(
      <View >
        <View style={{flexDirection:'row',alignItems:'flex-end'}}>
          <Text style={{color:this.props.color,fontSize:18}}>{this.props.num}</Text><Text>{this.props.unit}</Text>
        </View>
        <Text>{this.props.title}</Text>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  column2:{
    flex:2,
    textAlign:'center'
  }, 
  column3:{
    flex:3,
    textAlign:'center'
  },  
  rowHeader:{
    marginLeft:0,
    marginRight:0,
    paddingLeft:20,
    paddingRight:20,
    paddingTop:10,
    paddingBottom:10,
    borderBottomColor:'#ccc',
    borderBottomWidth:StyleSheet.hairlineWidth,
  },
  row:{
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center',
    marginLeft:20,
    marginRight:20,
    paddingTop:10,
    paddingBottom:10,
  },
  active:{
    backgroundColor:'#5dbcf9',
  },
  noActive:{
    backgroundColor:'#DDDDDD',
  },
  activeT:{
    color:'white',
  },
  noActiveT:{
    color:'#999',
  },
  switchView:{
    width:38,
    justifyContent:'center',
    alignItems:'center',
  },  
  switchText:{
    paddingTop:2,
    paddingBottom:2,
    fontSize:13,
  },
  day:{
    backgroundColor:'#DDDDDD',
    borderBottomRightRadius:5,
    borderTopRightRadius:5,
  },
  hour:{
    
    borderBottomLeftRadius:5,
    borderTopLeftRadius:5,
  },
  rightBtn:{
    flexDirection:'row',
    alignItems:'center',
    marginRight:20,
  },  
  titleStyle:{
    flexDirection:'row',
    justifyContent:'space-between',
    borderBottomColor:'#ccc',
    borderBottomWidth:StyleSheet.hairlineWidth,
  },  
  headerText:{
    fontSize:17,
    marginLeft:5,
  },
  header:{
    flexDirection:'row',
    justifyContent:'flex-start',
    alignItems:'center',
    paddingBottom:8,
    paddingTop:8,
    paddingLeft:15,
  },
  itemBox:{
    width:width,
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center',
    paddingLeft:10,
    paddingRight:10,
    paddingTop:15,
    paddingBottom:15,
  },  
  subTitle:{
    padding:5,
    fontSize:14,
  },
  headerStyle:{
    flexDirection:'row',
    alignItems:'center',
    borderBottomWidth:1,
    borderBottomColor:'#ccc',
    marginLeft:15,
  },  
  lefgImg:{
    width:width*0.2,
    height:width*0.2*1.23,
    marginLeft:10,
  },
  container:{
    flex:1,
  },
})